package com.fmatos.amazingwallpapers.service.image;

import android.app.IntentService;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.util.Log;

import com.fmatos.amazingwallpapers.dagger.AmazingApplication;
import com.fmatos.amazingwallpapers.image.CloudManager;
import com.fmatos.amazingwallpapers.image.database.dto.ImageRow;
import com.fmatos.amazingwallpapers.view.albums.AlbumsViewSource;
import com.fmatos.amazingwallpapers.view.detail.ImageDetail;

public class DownloadIntentService  extends IntentService{

	private static final String ACTION_DOWNLOAD_SINGLE_URL = "ACTION_DOWNLOAD_URL";
	private static final String ACTION_UPDATE_ALBUM_INFO = "ACTION_UPDATE_ALBUM_INFO";
    private static final String ACTION_DELETE_OLD_IMAGES = "ACTION_DELETE_OLD_IMAGES";
    private static final String ACTION_DOWNLOAD_MOST_IMAGES = "ACTION_DOWNLOAD_MOST_IMAGES";

	private static final String INTENT_EXTRA_URL = "INTENT_EXTRA_URL";
	private static final String INTENT_EXTRA_PARCELABLE = "INTENT_EXTRA_PARCELABLE";
	
	public static final String BUNDLE_RESULT_FILENAME = "BUNDLE_RESULT_FILENAME";
	
	private static final String TAG =  DownloadIntentService.class.getSimpleName();

	private CloudManager cloudManager;

	public DownloadIntentService(CloudManager cloudManager) {
        super("DownloadIntentService");
//        ((AmazingApplication) getApplication()).inject(this,null); // needs to add DownloadIntentService to inject section in module
        this.cloudManager = cloudManager;
    }
 	
	public static void downloadBitmap(Context context, ImageRow image, ResultReceiver results) {

		if ( image.getUrl() == null || image.getAlbum() == null) {
			Log.e(TAG,"Can't accept null url or album");
			return;
		}
		
		Intent msgIntent = new Intent(context, DownloadIntentService.class);
		msgIntent.setAction(ACTION_DOWNLOAD_SINGLE_URL);
		msgIntent.putExtra(INTENT_EXTRA_URL, image.getUrl());
		msgIntent.putExtra(ImageDetail.INTENT_EXTRA_ALBUM_ID, image.getAlbum());
		
		msgIntent.putExtra(INTENT_EXTRA_PARCELABLE, results);
		startActivity(context,msgIntent);
		
		
	}


    /**
     * Updates information for given album.
     * @param context
     * @param albumId if null, updates info for all albums
     * @param results
     */
	public static void updateAlbumInfo(Context context, String albumId,ResultReceiver results) {

		Intent msgIntent = new Intent(context, DownloadIntentService.class);
		msgIntent.setAction(ACTION_UPDATE_ALBUM_INFO);
		msgIntent.putExtra(INTENT_EXTRA_PARCELABLE, results);
		msgIntent.putExtra(ImageDetail.INTENT_EXTRA_ALBUM_ID, albumId);
		
		startActivity(context,msgIntent);
		
	}


    public static void downloadMostImages(Context context, Object o, ResultReceiver resultReceiver) {
        Intent msgIntent = new Intent(context, DownloadIntentService.class);
        msgIntent.setAction(ACTION_DOWNLOAD_MOST_IMAGES);
        msgIntent.putExtra(INTENT_EXTRA_PARCELABLE, resultReceiver);

        startActivity(context,msgIntent);

    }


    public static void deleteOldImages(Context context, Object o, ResultReceiver results) {
        Intent msgIntent = new Intent(context, DownloadIntentService.class);
        msgIntent.setAction(ACTION_DELETE_OLD_IMAGES);
        msgIntent.putExtra(INTENT_EXTRA_PARCELABLE, results);

        startActivity(context,msgIntent);

    }

	private static void startActivity(Context context,Intent msgIntent) {
		if ( context == null) {
			Log.e(TAG,"Can't accept null context");
			return;
		}
		
		ComponentName name = context.startService(msgIntent);
		
		Log.i(TAG,"Starting intent service " + name.toString());
	}
	
	
	@Override
	protected void onHandleIntent(Intent intent) {
		
		int resultCode = 0;
		
		Log.i(TAG,"Handling intent service");
		if ( ACTION_DOWNLOAD_SINGLE_URL.equals(intent.getAction()) ) {
			String url = (String)intent.getExtras().get(INTENT_EXTRA_URL);
			String albumName = (String)intent.getExtras().get(ImageDetail.INTENT_EXTRA_ALBUM_ID);
//			String filename = downloadSingleUrl(url,albumName);
//
//			ResultReceiver results = intent.getParcelableExtra(INTENT_EXTRA_PARCELABLE);
//			if ( results != null ) {
//				Bundle resultData = new Bundle();
//				
//				resultData.putString(BUNDLE_RESULT_FILENAME, filename);
//				results.send(resultCode , resultData );
//				
//			} else
//			Log.i(TAG,"Got it in file " + filename);
		} else if (ACTION_UPDATE_ALBUM_INFO.equals(intent.getAction())) {

			String albumName = (String)intent.getExtras().get(ImageDetail.INTENT_EXTRA_ALBUM_ID);
			// Do some actual work
			downloadAlbumInfo(albumName);
			ResultReceiver results = intent.getParcelableExtra(INTENT_EXTRA_PARCELABLE);
			if ( results != null ) {
				Bundle resultData = new Bundle();
				results.send(resultCode , resultData );
			}

		} else if (ACTION_DELETE_OLD_IMAGES.equals(intent.getAction())) {

            deleteOldBitmaps();
            ResultReceiver results = intent.getParcelableExtra(INTENT_EXTRA_PARCELABLE);
            if ( results != null ) {
                Bundle resultData = new Bundle();
                results.send(resultCode , resultData );
            }
        } else if (ACTION_DOWNLOAD_MOST_IMAGES.equals(intent.getAction())) {

            downloadImages();
            ResultReceiver results = intent.getParcelableExtra(INTENT_EXTRA_PARCELABLE);
            if ( results != null ) {
                Bundle resultData = new Bundle();
                results.send(resultCode , resultData );
            }

        }
		
	}

    private void deleteOldBitmaps() {
//        dataSource.deleteOldBitmaps();
//        dataSource.findLooseImages();

    }


    private void downloadAlbumInfo(String albumName) {

    	if ( albumName == null ) {
    		cloudManager.refreshAlbumList();
    	} 
    	cloudManager.refreshAlbumInfo(albumName);
    	
	}

    private void downloadImages() {
//        List<ImageRow> list = dataSource.getLatestImagesWithoutFiles();

//        for ( ImageRow image : list){
//            downloadSingleUrl(image.getUrl(),image.getAlbum());
//        }
    }


}
